﻿$ErrorState = 2
$ErrorMessage = ""
$Trace = ""
$Value = ""
$Error.Clear()


$VMTemplate = "%TEMPLATE%"
$VMHostGroupName = "%HOSTGROUP%"
$vm_diskspace = %DISKSPACE%
$VMName = "%VMNAME%"
$VMHost = ""
$Path = ""
$Value = ";"

           
try {
            
	Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager

    $Trace += 'Connecting to VMM Server...  \n'

	$VMMServer = Get-VMMServer -ComputerName localhost

    $VMHostGroup = Get-VMHostGroup -Name $VMHostGroupName

	$HostRatings = @(Get-VMHostRating -DiskSpaceGB $vm_diskspace -Template $VMTemplate -VMHostGroup $VMHostGroup -VMName $VMName | where { $_.Rating -gt 0 } | Sort-Object -property Rating -descending)
	If($HostRatings.Count -eq "0")
	{ 
		$ErrorState = 1
		$Trace += 'No hosts meet the requirements....  \n'	
		
		
	}
	else
	{
		$ErrorState = 0
		$Trace += 'Found host that meet the requirements..  \n'

		$VMHost = $HostRatings[0].VMHost.Name
		$Path = $HostRatings[0].PreferredVolume.Name
		$Value = $VMHost + ";" + $Path
	}

}
catch {
    $ErrorState = 2
    $ErrorMessage = $error[0].Exception.ToString()
}
Finally {
    $Trace += 'ErrorState:  ' + $ErrorState + ' \n'
    $Trace += 'ErrorMessage: ' + $ErrorMessage + ' \n'
   
}
            
$Results = @($ErrorState, $ErrorMessage, $Trace, $Value) 
Return $Results